// 欢迎信息
console.log('%c欢迎加入吉林大学招生协会！', 'color: #4e73df; font-size: 18px; font-weight: bold;');
console.log('%c在这里，你将遇见志同道合的伙伴，收获成长与感动。', 'color: #36b9cc; font-style: italic;');
console.log('%c让我们携手同行，共同书写属于我们的精彩篇章。', 'color: #1cc88a; font-style: italic;');
console.log('%c期待你的加入，为招生协会注入新的活力！', 'color: #4e73df; font-weight: bold;');

let retryCount = 0;
const maxRetries = parseInt(document.getElementById('retryCount').dataset.maxRetries || '3');
console.log('Retry limit from config:', maxRetries);

function drawQuestion() {
    const studentId = document.getElementById('studentId').value.trim();
    if (!studentId) {
        showError('请输入学号');
        return;
    }

    const formData = new FormData();
    formData.append('student_id', studentId);

    fetch('/draw', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Response data:', data);
        if (data.success) {
            document.getElementById('questionDisplay').style.display = 'block';
            displayQuestions(data.data.questions);
            retryCount = 0; // Reset retry count on new draw
            updateRetryCount();
        } else {
            showError(data.message || '抽题失败，请稍后重试');
        }
    })
    .catch(error => {
        console.error('Error details:', error);
        showError('抽题失败，请稍后重试');
    });
}

function retryDraw() {
    if (retryCount >= maxRetries) {
        showError('已达到最大重抽次数');
        return;
    }

    retryCount++;
    updateRetryCount();

    fetch('/redraw')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
                return;
            }
            displayQuestions(data.questions);
        })
        .catch(error => {
            console.error('Error:', error);
            showError('重新抽题失败，请稍后重试');
        });
}

function updateRetryCount() {
    const retryCountElement = document.getElementById('retryCount');
    if (!retryCountElement) return; // 如果元素不存在，直接返回
    
    if (maxRetries <= 0) {
        retryCountElement.textContent = '不允许重抽';
    } else {
        retryCountElement.textContent = `${retryCount}/${maxRetries}`;
    }
}

function displayQuestions(questions) {
    const questionsList = document.getElementById('questionContent');
    questionsList.innerHTML = '';

    questions.forEach((question, index) => {
        const questionDiv = document.createElement('div');
        questionDiv.className = 'question-item';
        questionDiv.innerHTML = `
            <div class="question-content">${index + 1}. ${question.content}</div>
        `;
        questionsList.appendChild(questionDiv);
    });
}

function showError(message) {
    const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
    document.getElementById('errorMessage').textContent = message;
    errorModal.show();
}
